package controllers

import (
	"encoding/json"
	"github.com/astaxie/beego"
	mqtt "github.com/eclipse/paho.mqtt.golang"
	"hello/lib/mqttLib"
	"log"
)

type SettingControllers struct {
	beego.Controller
}

type DeviceSetting struct {
	Temperature float32 `json:"temperature"`
	Speed       int `json:"speed"`
	Hour        int	`json:"hour"`
	Minute      int	`json:"minute"`
}

func (s *SettingControllers) Get() {

}

func (s *SettingControllers) Post() {

	// 首先判断用户是否有权限

	// 获取post请求数据
	data := s.Ctx.Input.RequestBody
	log.Print("post 请求数据为：" + string(data))
	var requestVal DeviceSetting
	err := json.Unmarshal(data, &requestVal)
	if err != nil {
		log.Printf("unmarshal json data error %s", err)
	}

	// mqtt
	client := mqttLib.NewMqttClient(mqttLib.DefaultMqttconfig, onMsgHandler)
	if token := client.Connect(); token.Wait() && token.Error() != nil {
		log.Printf("mqtt client connect error :%s", token.Error())
	}

	topic := "GATEWAYID" + mqttLib.Setting
	settingByte, err := json.Marshal(requestVal)
	if err != nil {
		log.Printf("json marshal error: %s", err)
	}
	// publish
	if token := client.Publish(topic, 0, false, settingByte); token.Wait() && token.Error() != nil {
		log.Printf("publish message error :%s", token.Error())
	}
	//if token :=s client.Subscribe(mqttLib.RealTimeData, 0, nil); token.Wait() && token.Error() != nil {
	//	log.Printf("subscribe topic error :%s", token.Error())
	//}
	client.Disconnect(3000)
}

func onMsgHandler(client mqtt.Client, msg mqtt.Message) {
	log.Printf("mqtt message :%s", msg)
}